﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Menu;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Menu
{
    public class UpdateMenuHandler : IRequestHandler<UpdateMenuCommand, ApiResult<int>>
    {
        IBaseRepository<MenuManageModel> menuRepo;
        IMapper mapper;

        public UpdateMenuHandler(IBaseRepository<MenuManageModel> menuRepo, IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var menu = menuRepo.GetAll().Where(c => c.Pid == request.Pid && c.MenuName == request.MenuName && !c.IsDeleted && c.Id != request.Id).Count();
            if (menu > 0)
            {

                res.Msg = "同一级菜单下名称不能重复";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);

            }
            var menus=menuRepo.GetAll().Where(x=>!x.IsDeleted && x.Id==request.Id).FirstOrDefault();
            if (menus == null)
            {
                res.Msg = "找不到编号";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);
            }
            menus = mapper.Map(request,menus);
            menus.Updator = request.Updator;
            menus.UpdatorDate = DateTime.Now;
            int a = menuRepo.Update(menus).Result;
            if (a > 0)
            {
                res.Msg = "修改菜单成功";
                res.Code = ApiEnum.Success;
                res.Datas = a;

            }
            else
            {
                res.Msg = "修改菜单失败";
                res.Code = ApiEnum.Fail;
                res.Datas = a;
            }
            return Task.FromResult(res);
        }
    }
}
